# Styled Components Plugin

import { SourceCode } from 'rspress/theme';

<SourceCode href="https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-styled-components" />

:::tip About styled-components
[styled-components](https://styled-components.com/) is a popular CSS-in-JS implementation library, which uses the new JavaScript feature [Tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) to write component CSS styles.
:::

Rsbuild provides compile-time support for styled-components, improve the debugging experience and add server-side rendering support to styled-components.

For details, please refer to [Rspack#styledComponents](https://rspack.dev/guide/features/builtin-swc-loader#rspackexperimentsstyledcomponents).

## Quick Start

### Install Plugin

You can install the plugin using the following command:

import { PackageManagerTabs } from '@theme';

<PackageManagerTabs command="add @rsbuild/plugin-styled-components -D" />

### Register Plugin

You can register the plugin in the `rsbuild.config.ts` file:

```ts title="rsbuild.config.ts"
import { pluginStyledComponents } from '@rsbuild/plugin-styled-components';

export default {
  plugins: [pluginStyledComponents()],
};
```

## Example

After registering the plugin, you can use styled-components to write styles:

```ts
import styled from 'styled-components';

const div = styled.div`
  color: red;
`;

console.log('div', div);
```

## Options

If you need to customize the compilation behavior of `styled-components`, you can use the following configs.

You can check the [styled-components documentation](https://styled-components.com/) to learn how to use it.

- **Type:**

```ts
type StyledComponentsOptions = {
  displayName?: boolean;
  ssr?: boolean;
  fileName?: boolean;
  meaninglessFileNames?: string[];
  namespace?: string;
  topLevelImportPaths?: string[];
  transpileTemplateLiterals?: boolean;
  minify?: boolean;
  pure?: boolean;
  cssProps?: boolean;
};
```

- **Default:**

```ts
{
  displayName: true,
  // `isSSR` is true in SSR build
  ssr: isSSR,
  // `pure` is enabled in production to reduce bundle size
  pure: isProd,
  transpileTemplateLiterals: true,
}
```

- **Example:**

When the value is an Object, use the `Object.assign` function to merge with the default config.

```ts title="rsbuild.config.ts"
export default {
  plugins: [
    pluginStyledComponents({
      pure: true,
    }),
  ],
};
```
